package com.bookmanger.server.service.impl;

import com.bookmanger.pojo.DTO.BookDTO;
import com.bookmanger.pojo.Entity.BookEntity;
import com.bookmanger.pojo.Entity.IsbnEntity;
import com.bookmanger.server.mapper.BookMapper;
import com.bookmanger.server.mapper.IsbnMapper;
import com.bookmanger.server.service.BookManagerService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class BookManagerServiceImpl implements BookManagerService {
    @Autowired
    private IsbnMapper isbnMapper;
    @Autowired
    private BookMapper bookMapper;

    @Override
    @Transactional
    public boolean addBook(BookDTO bookDTO) {
        IsbnEntity existingIsbn = isbnMapper.selectById(bookDTO.getId());
        if (existingIsbn == null) {
            IsbnEntity newIsbn = new IsbnEntity();
            BeanUtils.copyProperties(bookDTO, newIsbn);
            if (isbnMapper.insert(newIsbn) <= 0) {
                return false;
            }
            bookDTO.setId(newIsbn.getId());
        } else {
            isbnMapper.updateStock(existingIsbn.getId(), bookDTO.getStock());
            bookDTO.setId(existingIsbn.getId());
        }

        for (int i = 0; i < bookDTO.getStock(); i++) {
            BookEntity bookEntity = new BookEntity();
            bookEntity.setBookNumber("BK-" + System.currentTimeMillis() + "-" + i);
            bookEntity.setIsbnId(bookDTO.getId());
            if (bookMapper.insert(bookEntity) <= 0) {
                return false;
            }
        }
        return true;
    }

    @Override
    @Transactional
    public boolean deleteBookByBookNumber(String bookNumber) {
        BookEntity bookEntity = bookMapper.selectByBookNumber(bookNumber);
        if (bookEntity == null) {
            return false;
        }
        if (bookMapper.deleteByBookNumber(bookNumber) <= 0) {
            return false;
        }
        return isbnMapper.updateStock(bookEntity.getIsbnId(), -1) > 0;
    }
    
    @Override
    @Transactional
    public boolean deleteBookById(Integer id) {
        // 先删除关联的book表中的记录（逻辑删除）
        bookMapper.deleteByIsbnId(id);
        
        // 再删除isbn_tb表中的记录（逻辑删除）
        return isbnMapper.deleteById(id) > 0;
    }

    @Override
    public boolean updateBook(BookDTO bookDTO) {
        IsbnEntity isbnEntity = new IsbnEntity();
        BeanUtils.copyProperties(bookDTO, isbnEntity);
        return isbnMapper.update(isbnEntity) > 0;
    }

    @Override
    public BookDTO getBookById(Integer id) {
        IsbnEntity isbnEntity = isbnMapper.selectById(id);
        if (isbnEntity == null) {
            return null;
        }
        BookDTO bookDTO = new BookDTO();
        BeanUtils.copyProperties(isbnEntity, bookDTO);
        return bookDTO;
    }

    @Override
    public List<BookDTO> searchBooks(String keyword) {
        List<IsbnEntity> isbnList = isbnMapper.search(keyword);
        return isbnList.stream().map(isbn -> {
            BookDTO bookDTO = new BookDTO();
            BeanUtils.copyProperties(isbn, bookDTO);
            return bookDTO;
        }).collect(Collectors.toList());
    }

    @Override
    public List<BookDTO> getAllBooks() {
        List<IsbnEntity> isbnList = isbnMapper.findAll();
        return isbnList.stream().map(isbn -> {
            BookDTO bookDTO = new BookDTO();
            BeanUtils.copyProperties(isbn, bookDTO);
            return bookDTO;
        }).collect(Collectors.toList());
    }
    
    @Override
    public PageInfo<BookDTO> searchBooks(String keyword, Integer page, Integer pageSize) {
        // 使用PageHelper进行分页
        PageHelper.startPage(page, pageSize, true);
        List<IsbnEntity> isbnList = isbnMapper.search(keyword);
        List<BookDTO> bookList = isbnList.stream().map(isbn -> {
            BookDTO bookDTO = new BookDTO();
            BeanUtils.copyProperties(isbn, bookDTO);
            return bookDTO;
        }).collect(Collectors.toList());
        
        return new PageInfo<>(bookList);
    }
    
    @Override
    public PageInfo<BookDTO> getAllBooks(Integer page, Integer pageSize) {
        // 使用PageHelper进行分页，启用合理化参数
        PageHelper.startPage(page, pageSize, true);
        List<IsbnEntity> isbnList = isbnMapper.findAll();
        List<BookDTO> bookList = isbnList.stream().map(isbn -> {
            BookDTO bookDTO = new BookDTO();
            BeanUtils.copyProperties(isbn, bookDTO);
            return bookDTO;
        }).collect(Collectors.toList());
        
        return new PageInfo<>(bookList);
    }
    
    @Override
    public List<BookEntity> getBookEntitiesByIsbnId(Integer isbnId) {
        // 这里需要一个新的Mapper方法来获取指定ISBN ID的所有实体书
        // 暂时返回空列表，后续需要实现
        return bookMapper.selectByIsbnId(isbnId);
    }
    
    @Override
    @Transactional
    public boolean addBookEntities(Integer isbnId, Integer quantity) {
        // 增加指定数量的实体书
        for (int i = 0; i < quantity; i++) {
            BookEntity bookEntity = new BookEntity();
            // 生成唯一的图书编号
            bookEntity.setBookNumber("BK-" + isbnId + "-" + System.currentTimeMillis() + "-" + i);
            bookEntity.setIsbnId(isbnId);
            if (bookMapper.insert(bookEntity) <= 0) {
                return false;
            }
        }
        
        // 更新ISBN表中的库存数量
        return isbnMapper.updateStock(isbnId, quantity) > 0;
    }
    
    @Override
    @Transactional
    public boolean deleteBookEntity(Integer bookId) {
        BookEntity bookEntity = bookMapper.selectById(bookId);
        if (bookEntity == null) {
            return false;
        }
        
        // 删除实体书（逻辑删除）
        if (bookMapper.deleteById(bookId) <= 0) {
            return false;
        }
        
        // 更新ISBN表中的库存数量
        return isbnMapper.updateStock(bookEntity.getIsbnId(), -1) > 0;
    }
}